package org.coder.threadpool.framkwork.core.impl;

import org.coder.threadpool.framkwork.core.ThreadFactory;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 默认线程工厂
 *
 * @author idea
 * @data 2019/9/5
 */
public class DefaultThreadFactory implements ThreadFactory {


    public static final AtomicInteger poolIndex=new AtomicInteger(1);

    public static AtomicInteger threadIndex=new AtomicInteger(1);

    private ThreadGroup threadGroup;

    private String poolName="Default-pool-"+poolIndex.getAndIncrement()+"-thread-";

    /**
     * 创建线程组管理 安全策略
     */
    public DefaultThreadFactory() {
        SecurityManager securityManager = System.getSecurityManager();
        threadGroup= (securityManager!=null) ? securityManager.getThreadGroup() : Thread.currentThread().getThreadGroup();
    }

    @Override
    public Thread createThread(Runnable r) {
        //线程初始化的时候栈大小分配为0
        Thread newThread=new Thread(threadGroup,r,
                poolName+threadIndex.getAndIncrement(),
                0);
        //默认不创建守护线程
        if(newThread.isDaemon()){
            newThread.setDaemon(true);
        }
        if(newThread.getPriority()!=Thread.NORM_PRIORITY){
            newThread.setPriority(Thread.NORM_PRIORITY);
        }
        return newThread;
    }
}
